// pages/shopList/shopList.js
const util = require('../../utils/util.js')
const app = getApp();
const tempUrl = app.globalData.cloudUrl+"shopItem1.png";
const tempUrl2 = app.globalData.cloudUrl+"shopItem2.png";
import Toast from '../../dist/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    app:app,
    cloudUrl:app.globalData.cloudUrl,
    defaultTabs:[-1,-1],
    //底部菜单栏
    menus:[
      {id:1,name:"商城首页",num:0,imgs:["menu/menu_sc.png", "menu/menu_sc1.png"],img:"menu/menu_sc.png",txtColor:"#000000",param:""},
      {id:2,name:"全部分类",num:0,imgs:["menu/menu_fl.png", "menu/menu_fl1.png"],img:"menu/menu_fl.png",txtColor:"#000000",param:""},
      {id:3,name:"购物车",num:0,imgs:["menu/menu_gwc.png", "menu/menu_gwc1.png"],img:"menu/menu_gwc.png",txtColor:"#000000",param:"1"},
      {id:4,name:"附近店铺",num:0,imgs:["menu/menu_dp.png", "menu/menu_dp1.png"],img:"menu/menu_dp.png",txtColor:"#000000",param:""},
      {id:5,name:"商品订单",num:0,imgs:["menu/menu_dd.png", "menu/menu_dd1.png"],img:"menu/menu_dd.png",txtColor:"#000000",param:""}],
    titleArr:["特色商城","全部分类","购物车","附近门店",""],
    curTitle:"特色商城",
    hideArr:[true, false, true, true, true],
    //幻灯片
    //background: ['demo-text-1', 'demo-text-2', 'demo-text-3', 'demo-text-4'],
    background: [{"id":1, "name":"大木山景区"}, {"id":2, "name":"白马湖"}, {"id":3, "name":"驼峰景区"}],
    indicatorDots: false,
    vertical: false,
    autoplay: true,
    circular: false,
    interval: 2000,
    duration: 500,
    previousMargin: 0,
    nextMargin: 0,
    swiperUrls:["swiper2.png","swiper3.png","swiper4.png"],
    filterImg:"swiper2.png",
    testTxt:1,
    show:false,
    swiperBtnColors:["#d1cecd", "#d1cecd", "#d1cecd"],
    icons:[
      {id:1,name:"松阳茶叶",imgs:["shop-menu-icon10.png", "shop-menu-icon11.png"],img:"222",txtColor:"#000000",param:""},
      {id:2,name:"松阳文创",imgs:["shop-menu-icon10.png", "shop-menu-icon11.png"],img:"",txtColor:"#000000",param:""},
      {id:3,name:"松阳特产",imgs:["shop-menu-icon10.png", "shop-menu-icon11.png"],img:"",txtColor:"#000000",param:"1"},
      {id:4,name:"丽水好物",imgs:["shop-menu-icon10.png", "shop-menu-icon11.png"],img:"",txtColor:"#000000",param:""},],
    //店长推荐
    templateTitle:[{title:"店长推荐", img1:app.globalData.cloudUrl+'titleTag.png'},{title:"热门商品", img1:app.globalData.cloudUrl+'titleTag.png'}],
    //热门商品
    shops:[
      {id:1,name:"松阳茶叶",img:tempUrl,txtColor:"#000000",param:""},
      {id:2,name:"松阳文创",img:tempUrl,txtColor:"#000000",param:""},
      {id:3,name:"松阳特产",img:tempUrl,txtColor:"#000000",param:"1"},
      {id:4,name:"丽水好物",img:tempUrl,txtColor:"#000000",param:""}],
    bottomLinePos:900,
    isTipsShow:false,
    //----------全部分类-----------//
    shopDic:{},
    allMenus:[
      {id:1,name:"松阳茶叶",txtColor:"#000000",select:false},
      {id:2,name:"松阳特产",txtColor:"#000000",select:true},
      {id:3,name:"松阳文创",txtColor:"#000000",select:true},
      {id:4,name:"其他商品",txtColor:"#000000",select:true},
      {id:5,name:"松阳书籍",txtColor:"#000000",select:true},
      {id:6,name:"补邮费差",txtColor:"#000000",select:true},
      {id:7,name:"测试勿买",txtColor:"#000000",select:true}
    ],
    allMenus1:[
      {id:1,name:"茶叶",txtColor:"#000000",select:false, border: "2px solid rgba(65, 89, 224, 0.562)"},
      {id:2,name:"松阳特产",txtColor:"#000000",select:true}
    ],
    allCurMenuIndex:0,
    allCurMenu1Index:0,
    allShopList:[[
      {id:1,name:"松阳茶叶",img:tempUrl,txtColor:"#000000",hot:100, price:129, oldPrice:300},
      {id:2,name:"松阳文创",img:tempUrl2,txtColor:"#000000",hot:98, price:56, oldPrice:888},
      {id:3,name:"松阳特产",img:tempUrl2,txtColor:"#000000",hot:20, price:12, oldPrice:300},
      {id:4,name:"松阳特产",img:tempUrl,txtColor:"#000000",hot:45, price:63, oldPrice:300},
      {id:5,name:"松阳特产",img:tempUrl,txtColor:"#000000",hot:4, price:75, oldPrice:300},
      {id:6,name:"松阳特产",img:tempUrl2,txtColor:"#000000",hot:57, price:258, oldPrice:300},
      {id:7,name:"丽水好物",img:tempUrl,txtColor:"#000000",hot:8, price:21, oldPrice:300}],
      [
        {id:1,name:"松阳茶叶2",img:tempUrl,txtColor:"#000000",hot:25, price:466, oldPrice:300},
        {id:2,name:"松阳文创2",img:tempUrl2,txtColor:"#000000",hot:7, price:204, oldPrice:300},
        {id:3,name:"松阳特产2",img:tempUrl2,txtColor:"#000000",hot:10, price:36, oldPrice:300}]
    ],
    allShops:[],
    quickInfo:"",
    allShopSortType:0,//0普通id排序，1销量高，2销量低，3价格低，4价格高
    allSortColors:[{id:1,select:-1,color1:"#000000", color2:"#d7d7d7", color3:"#999999"},
                  {id:2,select:-1,color1:"#000000", color2:"#d7d7d7", color3:"#999999"}],
    //----------购物车-----------//
    cartRatioAll:false,
    cartList:[],
    totalPrice:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("shopList.js, onload test!!!")
    wx.setNavigationBarTitle({
      title: this.data.curTitle,
    })

    util.getAndSetUserInfo();
    try{
      var tabs = JSON.parse(options.tabs);
      if(tabs){
        this.setData({defaultTabs:tabs});
      }
    }
    catch(e){

    }

    //this.getDatabase();
    //this.refreshCart();

    /**setInterval(() => {
      this.setData({
        show:!this.data.show
      });
    }, 100);**/
  },
  getDatabase(){
    //获取商品数据列表
    const _this = this;
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data:{
        type:"getDataList",
        todos:"shopList"
      },
      complete: res => {
        console.log('get shopList: ', res);
        var infos = res.result.data;
        //allMenus,allMenus1,allShopList,
        var menus = [];
        var infoDic = {};
        var key,key2 = "";
        for(var i=0; i<infos.length; i++){
          key = infos[i].firstType;
          if(infoDic[key] == null){
            infoDic[key] = {secondMenu:[]};
            menus.push({id:1,name:key,txtColor:"#000000",select:false});
          }
          key2 = infos[i].secondType;
          if(infoDic[key][key2] == null){
            infoDic[key][key2] = [];
            infoDic[key].secondMenu.push({id:1,key1:key,name:key2,txtColor:"#000000",select:false});
          }
          infoDic[key][key2].push(infos[i]);
        }
        _this.setData({shopDic:infoDic,allMenus:menus});////
        _this.initFun();
      }
    })
  },
  onCirckeClick(e){
    util.gotoShopQuickPage(e);
  },
  onShopDetailsClick(e){
    const info = e.currentTarget.dataset.item;
    console.log("onShopDetailsClick",info);
    util.gotoShopDetailsPage(info);
  },
  initFun(){
    //console.log("sldkfjsldfdslkfdklsdklldsflk");
    //初始化图片
    var ms = this.data.menus;
    for(var i=0; i<ms.length; i++){
      ms[i].img = ms[i].imgs[0];
      ms[i].txtColor = "#000000";
      this.data.hideArr[i] = true;
    }
    ms[1].img = ms[1].imgs[1];
    this.data.hideArr[1] = false;
    ms[1].txtColor = "#6699ff";
    this.setData({menus:ms});
    //初始化位置,商城首页-热门商品
    var arr = this.data.shops;
    for(var i=0; i<arr.length; i++){
      if(i % 2 == 0){
        arr[i].posx = 0;
      }
      else{
        arr[i].posx = 360;
      }
      arr[i].posy = Math.floor(i / 2) * 470;
    }
    this.setData({shops:arr, bottomLinePos:arr[arr.length-1].posy+470,hideArr:this.data.hideArr});
    //初始化位置,全部分类-全部商品
    const tabs = this.data.defaultTabs;
    if(tabs[0] != -1){
      this.onMenuClick(null, tabs[0]);
      if(tabs[0] == 1){
        var index = tabs[1] == -1 ? 0 : tabs[1];
        this.onAllMenuClick(null, index);
      }
    }
    
  },
  onMenuClick(e, index=-1){
    var ms = this.data.menus;
    var idx = 0;
    if(index != -1){
      idx = index;
    }
    else{
      idx = e.currentTarget.dataset.index;
    }
    if(idx == 0 || idx == 3){
      Toast("功能暂未开放");
      return;
    }
    if(idx >= 4){
      util.gotoOrderGoodsPage(1);
      return;
    }
    if(idx == 2){//购物车
      this.refreshCart();
    }
    console.log(e);
    for(var i=0; i<ms.length-1; i++){
      this.data.hideArr[i] = true;
      if(idx == i){
        ms[i].img = ms[i].imgs[1];
        ms[i].txtColor = "#6699ff";
        this.data.hideArr[i] = false;
      }
      else{
        ms[i].img = ms[i].imgs[0];
        ms[i].txtColor = "#000000";
      }
    }
    var tt = this.data.curTitle;
    this.setData({menus:ms, curTitle:tt, hideArr:this.data.hideArr});
    wx.setNavigationBarTitle({
      title: tt,
    })
  },
  refreshCart(){
    const app = getApp();
    const key = "shopcart_" + app.globalData.openid;
    var arr = null;
    const _this = this;
    wx.getStorage({
      key: key,
      complete(res) {
        console.log("get storage11,",res);
        arr = res.data;
        if(arr && arr.length > 0){
          //_this.data.cartList.carts = arr;
          //console.log(_this.data.cartList.carts);
          var arr1 = arr.concat();
          _this.setData({cartList:arr1});
          _this.refreshCartNum();
        }
      }
    });
  },
  refreshCartNum(){
    const carts = this.data.cartList;
    const menus = this.data.menus;
    menus[2].num = carts.length;
    console.log("refreshCartNum->",carts);
    this.setData({menus:menus});
  },
  onSwiperChange(e){
    //console.log("幻灯片滑动了。" + e.detail.current)
    //this.data.testTxt = ""+e.detail.current;
    var colors = this.data.swiperBtnColors;
    const index = e.detail.current;
    for(var i=0; i<colors.length; i++){
      if(index == i){
        colors[i] = "#ff0000";
      }
      else{
        colors[i] = "#d1cecd";
      }
    }
    this.setData({
      testTxt:""+e.detail.current,
      filterImg:this.data.swiperUrls[e.detail.current],
      swiperBtnColors:colors
    })
  },
  onBtnClick(){
    this.setData({
      show:!this.data.show
    });
    console.log("bool="+this.data.show);
  },
  onQuickClick(e){
    var info = e.currentTarget.dataset.item;
    info = JSON.stringify(info);
    console.log(info);
    this.setData({quickInfo:info});
    this.setData({isTipsShow:!this.data.isTipsShow});
  },
  onNotesEvent(e){
    //console.log(e);
    if(e.detail.type == "close"){
      this.setData({isTipsShow:false});
    }
    else if(e.detail.type == "confirm"){
      if(e.detail.select && e.detail.num > 0){
        this.setData({isTipsShow:false});
        //do something...
        
        // 存入本地缓存
        const app = getApp();
        const _this = this;
        const key = "shopcart_" + app.globalData.openid;
        var arr = null;
        wx.getStorage({
          key: key,
          complete(res) {
            console.log("get storage,",res);
            arr = res.data;
            if(!arr){
              arr = [];
            }
            //console.log(e);
            const item = e.detail.item;
            item.buyNum = e.detail.num;
            arr.push(item);
            _this.setData({cartList:arr});
            _this.refreshCartNum();

            //插入
            wx.setStorage({
              key: key,
              data: arr,
              success() {
                Toast("加入购物车成功!");
              }
            })
          }
        })
      }
      else{
        Toast("请选择商品规格和属性");
      }
    }
  },
  //----------------全部分类---------------//
  onAllMenuClick(e, index=-1){
    var idx = 0;
    if(index >= 0){
      idx = index;
    }
    else{
      idx = e.currentTarget.dataset.index;
    }
    this.data.allCurMenuIndex = idx;
    const menus = this.data.allMenus;
    var menu = null;
    for(var i=0; i<menus.length; i++){
      menu = menus[i];
      if(idx == i){
        menu.select = false;
        menu.txtColor = "rgb(102,153,255)";
        menu.bgColor = "white";
      }
      else{
        menu.select = true;
        menu.txtColor = "rgb(0,0,0)";
        menu.bgColor = "";
      }
    }
    const key = menus[idx].name;
    console.log("key="+key);
    const arr = this.data.shopDic[key].secondMenu;
    this.setData({allMenus:this.data.allMenus,allMenus1:arr});
    this.onAllMenu1Click(null, 0);
  },
  onAllMenu1Click(e, index=-1){
    var idx = 0;
    if(index >= 0){
      idx = index;
    }
    else{
      idx = e.currentTarget.dataset.index;
    }
    this.data.allCurMenu1Index = idx;
    const menus = this.data.allMenus1;
    var menu = null;
    for(var i=0; i<menus.length; i++){
      menu = menus[i];
      if(idx == i){
        menu.select = true;
        menu.border = "2px solid rgba(65, 89, 224, 0.562)";
      }
      else{
        menu.select = false;
        menu.border = "";
      }
    }
    //shopDic
    const obj = menus[idx];
    const arr = this.data.shopDic[obj.key1][obj.name];
    console.log("切换=",arr);
    this.data.allShops = arr;
    this.setData({allMenus1:this.data.allMenus1, allShopList:arr, allShops:this.data.allShops});
    this.onShopsRefresh();//
  },
  onShopsRefresh(){
    var arr = this.data.allShops.concat();
    const sortType = this.data.allShopSortType;
    if(sortType == 0){
      arr = util.sortArray(arr, "id");
    }
    else if(sortType == 1){
      arr = util.sortArray(arr, "sold", true);
    }
    else if(sortType == 2){
      arr = util.sortArray(arr, "sold");
    }
    else if(sortType == 3){
      arr = util.sortArray(arr, "price");
    }
    else if(sortType == 4){
      arr = util.sortArray(arr, "price", true);
    }
    for(var i=0; i<arr.length; i++){
      if(i % 2 == 0){
        arr[i].posx = 0;
      }
      else{
        arr[i].posx = 290;
      }
      arr[i].posy = Math.floor(i / 2) * 420;
    }
    this.setData({allShops:arr});
  },
  onSortClick(e){
    const idx = e.currentTarget.dataset.index;
    console.log(idx);
    //color1:"#000000", color2:"#d7d7d7", color3:"#999999"
    var infos = this.data.allSortColors;
    var info = null;
    for(var i=0; i<infos.length; i++){
      info = infos[i];
      if(idx == i){
        if(info.select == 0){
          info.select = 1;
          info.color1 = "#6699ff";
          info.color3 = "#6699ff";
          info.color2 = "#a0c0ff";
        }
        else{
          info.select = 0;
          info.color1 = "#6699ff";
          info.color2 = "#6699ff";
          info.color3 = "#a0c0ff";
        }
        this.data.allShopSortType = i * 2 + 1 + info.select;
      }
      else{
        info.select = -1;
        info.color1 = "#000000";
        info.color2 = "#d7d7d7";
        info.color3 = "#999999";
      }
    }
    this.setData({allSortColors:this.data.allSortColors});
    this.onShopsRefresh();
  },

  //----------------购物车---------------//
  onCartStepChange(e){
    //console.log("onCartStepChange,",e);
    const num = e.detail;
    const idx = e.currentTarget.dataset.index;
    var info = this.data.cartList[idx];
    info.buyNum = num;
    this.setData({
      cartList:this.data.cartList
    });
    this.refreshPrice();
  },
  onCartRatioClick(e){
    const idx = e.currentTarget.dataset.index;
    var info = this.data.cartList[idx];
    info.select = !info.select;
    this.setData({
      cartList:this.data.cartList
    });
    this.refreshPrice();
  },
  onCartRatioAllClick(e){
    var total = 0;
    var allselect = !this.data.cartRatioAll;
    const list = this.data.cartList;
    for(var i=0; i<list.length; i++){
      list[i].select = allselect;
      total += list[i].buyNum * list[i].price;
    }
    this.setData({
      totalPrice:total,
      cartRatioAll:allselect,
      cartList:this.data.cartList
    });
  },
  refreshPrice(){
    var total = 0;
    const list = this.data.cartList;
    for(var i=0; i<list.length; i++){
      if(list[i].select){
        total += list[i].buyNum * list[i].price;
      }
    }
    this.setData({totalPrice:total});
  },
  onPayClick(e){
    var list = this.data.cartList;
    var arr = [];
    for(var i=0; i<list.length; i++){
      if(list[i].select){
        arr.push(list[i]);
      }
    }
    if(arr.length > 0){
      util.gotoShopSubmitPage(arr);
    }
    else{
      Toast("请先选择商品！");
    }
  },
  onDeleteClick(e){
    var list = this.data.cartList;
    var flag = false;
    for(var i=0; i<list.length; i++){
      if(list[i].select){
        flag = true;
        list.splice(i, 1);
        i --;
      }
    }
    if(!flag){
      Toast("请选择需要删除的商品！");
    }
    else{
      this.setData({cartList:list});
      const _this = this;
      const app = getApp();
      const key = "shopcart_" + app.globalData.openid;
      wx.setStorage({
        key: key,
        data: list,
        success() {
          Toast("物品删除成功!");
          _this.refreshCartNum();
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //this.initFun();
    console.log("shopList.js, onShow test!!!");
    this.getDatabase();
    this.refreshCart();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})